package cn.trigram.web;

import cn.trigram.feign.EchoService;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.context.ContextUtil;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@Slf4j
@RefreshScope
@Setter(onMethod_ = {@Autowired})
@RestController
public class EchoController {

  private LoadBalancerClient loadBalancerClient;

  private RestTemplate restTemplate;

  @Setter
  @Value("${appName:app}")
  private String appName;

  @GetMapping("/echo/app-name")
  public String echoAppName() {
    //使用 LoadBalanceClient 和 RestTemplate 结合的方式来访问
    ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-service02");
    String url = String.format("http://%s:%s/echo/%s",
                               serviceInstance.getHost(),
                               serviceInstance.getPort(), appName
    );
    /*不能再使用这个restTemplate请求绝对地址了*/
    return restTemplate.getForObject(url, String.class);
  }

}
